package web

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
	"time"
)

// CreatWxUser 添加微信用户
func CreatWxUser(c *gin.Context) {
	DB := common.GetDB()
	telephone := c.PostForm("telephone")
	companyPhone := c.PostForm("companyPhone")
	userTime := c.PostForm("userTime")
	paperId := c.PostForm("paperId")
	adminPhone := c.PostForm("adminPhone")
	if len(telephone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "传入的手机号不正确")
		return
	} else if len(companyPhone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "传入的公司手机号不正确")
		return
	} else if paperId == "" {
		response.Reponse(c, http.StatusOK, 422, nil, "请选择真题")
		return
	} else if userTime == "" {
		response.Reponse(c, http.StatusOK, 422, nil, "请选择会员时间")
		return
	}
	if isCompanyExits(DB, companyPhone) {
		if WxUserTelephoneExits(DB, telephone) {
			response.Reponse(c, http.StatusOK, 422, nil, "该手机号已经被注册")
			return
		} else {
			nowTime := time.Now()
			if userTime == "three" {
				newTime := nowTime.AddDate(0, 0, 3)
				wxUser := model.WxUser{
					Telephone:    telephone,
					CompanyPhone: companyPhone,
					UserTime:     newTime,
					PaperId:      paperId,
					AdminPhone:   adminPhone,
				}
				DB.Create(&wxUser)
				response.Reponse(c, http.StatusOK, 200, gin.H{"newTime": newTime}, "添加成功")
				return
			} else {
				newTime := nowTime.AddDate(0, 0, 15)
				wxUser := model.WxUser{
					Telephone:    telephone,
					CompanyPhone: companyPhone,
					UserTime:     newTime,
					PaperId:      paperId,
					AdminPhone:   adminPhone,
				}
				DB.Create(&wxUser)
				response.Reponse(c, http.StatusOK, 200, gin.H{"newTime": newTime}, "添加成功")
				return
			}
		}
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "传入的公司手机号不存在")
		return
	}
}

func isCompanyExits(db *gorm.DB, companyPhone string) bool {
	var company model.Company
	db.Where("telephone = ?", companyPhone).First(&company)
	if company.ID != 0 {
		return true
	}
	return false
}
func WxUserTelephoneExits(db *gorm.DB, telephone string) bool {
	var wxUser model.WxUser
	db.Where("telephone = ?", telephone).First(&wxUser)
	if wxUser.ID != 0 {
		return true
	}
	return false
}
